package email.becode.simultaneous_interpretation_android.translation

import com.alibaba.dashscope.audio.asr.translation.TranslationRecognizerParam
import com.alibaba.dashscope.audio.asr.translation.TranslationRecognizerRealtime
import com.alibaba.dashscope.audio.asr.translation.results.TranslationRecognizerResult
import com.alibaba.dashscope.common.ResultCallback
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.channels.onFailure
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.catch
import timber.log.Timber
import java.nio.ByteBuffer
import java.util.concurrent.atomic.AtomicBoolean

class TranslationService {
    private var recognizer: TranslationRecognizerRealtime? = null
    private val isServiceRunning = AtomicBoolean(false)
    private val isServiceInitialized = AtomicBoolean(false)

    data class TranslationResult(
        val sourceText: String,
        val translations: Map<String, String>,
        val isFinal: Boolean
    )

    fun startTranslation(
        sourceLanguage: String,
        targetLanguages: List<String>,
        apiKey: String
    ): Flow<TranslationResult> = callbackFlow {
        try {
            if (!isServiceRunning.compareAndSet(false, true)) {
                throw IllegalStateException("翻译服务已经在运行")
            }

            Timber.d("开始翻译服务 - 源语言: $sourceLanguage, 目标语言: $targetLanguages")
            
            val param = TranslationRecognizerParam.builder()
                .apiKey(apiKey)
                .model("gummy-realtime-v1")
                .format("pcm")
                .sampleRate(16000)
                .transcriptionEnabled(true)
                .sourceLanguage(sourceLanguage)
                .translationEnabled(true)
                .translationLanguages(targetLanguages.toTypedArray())
                .build()
            
            Timber.d("翻译参数配置完成")

            val callback = object : ResultCallback<TranslationRecognizerResult>() {
                override fun onEvent(result: TranslationRecognizerResult) {
                    try {
                        if (!isServiceRunning.get()) {
                            Timber.w("翻译服务已停止，忽略结果")
                            return
                        }

                        val translations = mutableMapOf<String, String>()
                        
                        // 获取源语言识别结果
                        val sourceText = result.transcriptionResult?.text ?: ""
                        
                        // 获取各目标语言的翻译结果
                        targetLanguages.forEach { lang ->
                            result.translationResult?.getTranslation(lang)?.text?.let { text ->
                                translations[lang] = text
                            }
                        }

                        val translationResult = TranslationResult(
                            sourceText = sourceText,
                            translations = translations,
                            isFinal = result.isSentenceEnd
                        )
                        
                        Timber.d("收到翻译结果 - 源文本: $sourceText, 翻译: $translations, 是否结束: ${result.isSentenceEnd}")
                        
                        trySend(translationResult).onFailure { e ->
                            Timber.e(e, "发送翻译结果失败")
                            stopTranslation()
                        }
                    } catch (e: Exception) {
                        Timber.e(e, "处理翻译结果时发生错误")
                        stopTranslation()
                    }
                }

                override fun onError(e: Exception) {
                    Timber.e(e, "翻译过程中发生错误")
                    stopTranslation()
                    close(e)
                }

                override fun onComplete() {
                    Timber.i("翻译服务完成")
                    stopTranslation()
                    close()
                }
            }

            Timber.d("初始化翻译服务")
            recognizer = TranslationRecognizerRealtime()
            
            Timber.d("启动翻译服务")
            recognizer?.call(param, callback)
            isServiceInitialized.set(true)

            awaitClose {
                Timber.d("关闭翻译服务")
                stopTranslation()
            }
        } catch (e: Exception) {
            Timber.e(e, "翻译服务启动失败")
            stopTranslation()
            throw e
        }
    }.catch { e ->
        Timber.e(e, "翻译服务异常")
        stopTranslation()
        throw e
    }

    fun sendAudioData(audioData: ByteArray) {
        try {
            if (!isServiceRunning.get() || !isServiceInitialized.get()) {
                Timber.w("翻译服务未运行或未初始化完成，忽略音频数据")
                return
            }

            if (audioData.isEmpty()) {
                Timber.w("收到空的音频数据")
                return
            }

            Timber.v("发送音频数据: ${audioData.size} bytes")
            val buffer = ByteBuffer.wrap(audioData)
            recognizer?.sendAudioFrame(buffer)
        } catch (e: Exception) {
            Timber.e(e, "发送音频数据失败")
            stopTranslation()
        }
    }

    fun stopTranslation() {
        try {
            if (isServiceRunning.compareAndSet(true, false)) {
                Timber.d("停止翻译服务")
                recognizer?.stop()
                recognizer = null
            }
            isServiceInitialized.set(false)
        } catch (e: Exception) {
            Timber.e(e, "停止翻译服务时发生错误")
        } finally {
            isServiceRunning.set(false)
            isServiceInitialized.set(false)
        }
    }

    companion object {
        const val LANGUAGE_CHINESE = "zh"
        const val LANGUAGE_ENGLISH = "en"
        const val LANGUAGE_CANTONESE = "yue"
    }
}